<template>
  <basic-dialog
    width="70%"
    :title="dialogTitle"
    :visible="visible"
    :handleClose="handleCloseDialog"
  >
    <el-row>
      <slot name="warningMsg"></slot>
      <h4 style="color: #E6A23C;">你确定要批量操作吗？请填写原因</h4>
    </el-row>
    <el-form
      ref="formData"
      label-width="120px"
      class="input--reason--wrap"
      :model="formData"
      :rules="formRules"
    >
      <el-form-item prop="commitReasonType" :label="`${selectLabel}：`">
        <el-select v-model="formData.commitReasonType" clearable>
          <el-option
            v-for="option in reasonOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="commitReason" label="原因详情：">
        <el-input
          type="textarea"
          resize="none"
          v-model.trim="formData.commitReason"
          placeholder="请输入原因详情"
          :autosize="{ minRows: 3, maxRows: 4 }"
          :maxlength="100"
          show-word-limit
        />
      </el-form-item>
      <el-form-item v-if="this.isShowOARecord" prop="regionAdviceRecordNo" label="OA单号：">
        <el-input v-model="formData.regionAdviceRecordNo"></el-input>
      </el-form-item>
      <el-form-item v-if="this.isDownSku" prop="expectUpDate" label="预计上架时间：">
        <el-date-picker
          v-model="formData.expectUpDate"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item v-if="isFactoryShutdown" label="附件：" required>
        <el-radio-group v-model="uploadType" @change="handleChangeUploadType">
          <el-radio :label="attachmentTypes.File">文件</el-radio>
          <el-radio :label="attachmentTypes.Image">图片</el-radio>
        </el-radio-group>
        <UploadAttachement
          ref="uploadRef"
          :is-file="uploadType == attachmentTypes.File"
          :defaultFiles.sync="uploadAttachment.defaultFiles"
        />
      </el-form-item>
    </el-form>
    <el-row slot="ft" type="flex" justify="center">
      <el-button
        type="primary"
        v-preventReClick
        :loading="submitLoading"
        @click="handleOk">确定</el-button
      >
      <el-button
        v-preventReClick
        @click="handleCancel"
      >取消</el-button>
    </el-row>
  </basic-dialog>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import UploadAttachement from './UploadAttachement';
import { STOP_REASON_OPTIONS, DOWN_REASON_OPTIONS } from '@/constants/commodity';
import { ATTACHEMENT_TYPE } from './constants';
export default {
  components: {
    BasicDialog,
    UploadAttachement
  },
  props: {
    visible: { // 弹框显隐开关
      type: Boolean,
      required: true
    },
    submitLoading: { // 确定按钮loading
      type: Boolean,
      default: false
    },
    handleSubmit: { // 确定按钮点击触发方法
      type: Function,
      default: () => {}
    },
    isStopSku: { // 是停用商品，默认不是，默认是下架商品
      type: Boolean,
      default: false
    },
    hasSales: { // 有无销量
      type: Boolean,
      default: false
    },
    specialSubmit: {
      type: Function
    }
  },
  data () {
    return {
      formData: {
        commitReasonType: '',
        commitReason: '', // 原因详情
        regionAdviceRecordNo: '',
        expectUpDate: ''
      },
      formRules: {},
      reasonOptions: [],
      pickerOptions: {
        disabledDate: (time) => {
          const MAX_DAYS_LIMIT = 14 * 24 * 3600 * 1000;
          const isSmaller = time.getTime() <= new Date().getTime();
          const isMoreThan = time.getTime() > new Date().getTime() + MAX_DAYS_LIMIT;
          return isSmaller || isMoreThan;
        }
      },
      uploadType: ATTACHEMENT_TYPE.File,
      attachmentTypes: ATTACHEMENT_TYPE,
      uploadAttachment: {
        defaultFiles: []
      }
    }
  },
  computed: {
    isDownSku () {
      return !this.isStopSku;
    },
    dialogTitle () {
      if (this.isStopSku) return '批量停用';
      if (this.isDownSku) return '批量下架';
      return '批量操作';
    },
    selectLabel () {
      if (this.isStopSku) return '停用原因';
      if (this.isDownSku) return '下架原因';
      return '下架原因';
    },
    isShowOARecord () {
      // 档次调整、取消品牌合作”两种类型展示该字段
      const canShowTypes = ['7', '8'];
      const isEligible = canShowTypes.includes(this.formData.commitReasonType);
      return this.isStopSku && isEligible;
    },
    // 是厂家停产
    isFactoryShutdown () {
      const isFlag = this.formData.commitReasonType == '1'
      return isFlag
    }
  },
  watch: {
    visible (val) {
      if (val) this.initRelativeInfo();
    }
  },
  methods: {
    // 上传类型切换
    handleChangeUploadType (val) {
      this.uploadAttachment.defaultFiles = []
    },
    // 提交
    handleOk () {
      const endingExecutor = () => {
        this.handleCloseDialog();
        this.clearAllState();
      }
      this.$refs['formData'].validate(async valid => {
        if (valid) {
          // 停用所需参数
          const STOP_DATA = {
            ..._.omit(this.formData, 'expectUpDate'),
            attachmentInfo: {
              attachmentType: this.uploadType,
              detailList: this.uploadAttachment.defaultFiles.map(item => ({
                url: item?.fileKey,
                attachmentName: item?.name,
              }))
            }
          }
          const DOWN_DATA = _.omit(this.formData, 'regionAdviceRecordNo') // 下架所需参数
          const data = this.isStopSku ? STOP_DATA : DOWN_DATA;
          if (this.specialSubmit) return this.specialSubmit(data, endingExecutor)
          const retStatus = await this.handleSubmit(data)
          if (retStatus) endingExecutor()
        } else {
          this.$message.warning('必填项不能为空');
        }
      })
    },
    // 取消
    handleCancel () {
      this.handleCloseDialog()
    },
    // 关闭弹框
    handleCloseDialog () {
      this.$emit('update:visible', false)
    },
    // 清空状态
    clearAllState () {
      this.$refs.formData.resetFields()
      this.$refs.uploadRef.clearState()
    },
    // 初始化弹框数据
    initRelativeInfo () {
      this.reasonOptions = this.isStopSku ? STOP_REASON_OPTIONS : DOWN_REASON_OPTIONS
      this.formRules = {
        commitReasonType: { required: true, message: `${this.selectLabel}必填`, trigger: 'change' },
        regionAdviceRecordNo: { required: this.hasSales, message: 'OA单号必填', trigger: 'blur' },
        expectUpDate: { required: this.isDownSku, message: '预计上架时间必填', trigger: 'change' }
      };
      // 每次进入弹框，移除之前的校验结果
      this.$nextTick(() => {
        this.$refs.formData.clearValidate()
      })
    }
  }
}
</script>
<style lang="less" scoped>
.input--reason--wrap {
  margin-top: 10px;
}
</style>
